//
//  OSSHelper.m
//  FKGW
//
//  Created by song ce on 2017/3/28.
//  Copyright © 2017年 song ce. All rights reserved.
//

//上传图片的大小限制
//图片类型
//图片url传给后台的方式

#import "OSSHelper.h"
#import "AppDelegate.h"

static NSString *const AccessKey = @"LTAI8nxqAwt2ldSW";
static NSString *const SecretKey = @"ZcV18JFSwuy782bySD1FdHaQolSehh";
static NSString *const Endpoint = @"oss-cn-beijing.aliyuncs.com";
static NSString *const Bucket = @"cfkjcommon1";

static OSSHelper * instance=nil;
@implementation OSSHelper

//单利获取帮助对象
+ (instancetype)sharedHelper {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    return instance;
}

-(instancetype)init{
    if ((self = [super init])) {
        NSString *endpoint = [NSString stringWithFormat:@"https://%@",Endpoint];
        // 明文设置secret的方式建议只在测试时使用，更多鉴权模式参考后面链接给出的官网完整文档的`访问控制`章节
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:AccessKey secretKey:SecretKey];
        _client = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credential];
    }
    return self;
}

//异步上传图片
-(void)OSSUploadImageWithImage:(UIImage*)image path:(NSString*)path resultBlock:(resultBlock)resultBlock{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    if(image.size.width>Main_Screen_Width){
        image = [self scaleImage:image toScale:(float)Main_Screen_Width/image.size.width];
    }
    // 设置回调参数
//    put.callbackParam = @{
//                              @"callbackUrl": @"<your server callback address>",
//                              @"callbackBody": @"<your callback body>"
//                              };
    
    // 设置自定义变量
//    put.callbackVar = @{
//                            @"<var1>": @"<value1>",
//                            @"<var2>": @"<value2>"
//                            };
    
    put.bucketName = Bucket;
    //图片的类型
    NSData *imageData;
    NSString *objectKey;
//    if(UIImagePNGRepresentation(image)){//返回为png图像
//         imageData = UIImagePNGRepresentation(image);
//         objectKey = [NSString stringWithFormat:@"%@/%@.png",path,[self getUid]];
//    }else{ //返回为JPEG图像
         imageData = UIImageJPEGRepresentation(image, 1);
        objectKey = [NSString stringWithFormat:@"%@/%@.jpg",path,[self getUid]];
//    }
    DLog(@"--1--%zd",imageData.length/1024);
    if(imageData.length>1024*1024){
        imageData = UIImageJPEGRepresentation(image, .1);
        DLog(@"--2--%zd",imageData.length/1024);
    }
    put.objectKey = objectKey;
    put.uploadingData = imageData;
    //optional
//    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//        DLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//    };
    OSSTask * putTask = [_client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        DLog(@"objectKey: %@", put.objectKey);
        if (!task.error) {
            resultBlock(objectKey);
            DLog(@"--上传成功!");
        } else {
            DLog(@"上传失败, error: %@" , task.error);
        }
        return nil;
    }];
}

//异步下载  
-(void)OSSDownLoadWithObjectKey:(NSString*)objectKey  downLoadBlock:(downLoadBlock)downLoadBlock{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    // required
    request.bucketName = Bucket;
    request.objectKey = objectKey;
    
    //optional
//    request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
//        DLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
//    };
    // NSString * docDir = [self getDocumentDirectory];
    // request.downloadToFileURL = [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:@"downloadfile"]];
    
    OSSTask * getTask = [_client getObject:request];
    [getTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
        DLog(@"download object success!");
            OSSGetObjectResult * getResult = task.result;
            downLoadBlock(getResult.downloadedData);
            DLog(@"download dota length: %lu", [getResult.downloadedData length]);
        } else {
            DLog(@"download object failed, error: %@" ,task.error);
        }
        return nil;
    }];
}


//异步下载
-(void)OSSDownLoadWithObjectKey:(NSString*)objectKey xOssProcess:(NSString*)xOssProcess downLoadBlock:(downLoadBlock)downLoadBlock{
    OSSGetObjectRequest * request = [OSSGetObjectRequest new];
    request.bucketName = Bucket;
    request.objectKey = objectKey;
    request.xOssProcess =xOssProcess;
    //    @"image/resize,m_lfit,w_20,h_20";
    [self queryCashWithObjectKey:objectKey requst:request downLoadBlock:downLoadBlock];
}
//缓存
-(void)queryCashWithObjectKey:(NSString *)objectKey  requst:(OSSGetObjectRequest*)request  downLoadBlock:(downLoadBlock)downLoadBlock{
    
    NSString *key = [NSString stringWithFormat:@"%@%@",objectKey,request.xOssProcess];
    if(self.imageDic[key]){//内存中有
        downLoadBlock(self.imageDic[key]);
    }else{
        if(!self.operationDic[key]){
            [self.operationDic setObject:request forKey:key];
            //下载
            OSSTask * getTask = [_client getObject:request];
            __weak typeof(self) weakSelf = self;
            [getTask continueWithBlock:^id(OSSTask *task) {
                if (!task.error) {
                    DLog(@"download object success!");
                    [weakSelf.operationDic removeObjectForKey:key];
                    OSSGetObjectResult * getResult = task.result;
                    [weakSelf.imageDic setObject:getResult.downloadedData forKey:key];
                    downLoadBlock(getResult.downloadedData);
                    DLog(@"当前总量---%ld",weakSelf.imageDic.allKeys.count);
                    if(weakSelf.imageDic.allKeys.count>100){
                        for(int i=0;i<5;i++){
                            NSString *key = weakSelf.imageDic.allKeys[i];
                            [weakSelf.imageDic removeObjectForKey:key];
                        }
                        DLog(@"当前总量---%ld",weakSelf.imageDic.allKeys.count);
                    }
                    DLog(@"download dota length: %lu", [getResult.downloadedData length]);
                } else {
                    DLog(@"download object failed, error: %@" ,task.error);
                }
                return nil;
            }];
        }
    }
}
-(NSString*)getUid{
    return [AppDelegate appDealegate].uid;
}
- (NSString *)getTimeNow
{
    NSString* date;
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    date = [formatter stringFromDate:[NSDate date]];
    //取出个随机数
    int last = arc4random() % 10000;
    NSString *timeNow = [[NSString alloc] initWithFormat:@"%@-%d", date,last];
    DLog(@"当前时间%@", timeNow);
    return timeNow;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}


-(NSMutableDictionary *)operationDic{
    if(_operationDic==nil){
        _operationDic = [NSMutableDictionary dictionary];
    }
    return _operationDic;
}

-(NSMutableDictionary *)imageDic{
    if(_imageDic==nil){
        _imageDic = [NSMutableDictionary dictionary];
    }
    return _imageDic;
}


@end
